package com.example.nowcodercommunity.controller;

import com.example.nowcodercommunity.annotation.LoginRequire;
import com.example.nowcodercommunity.dao.CommentMapper;
import com.example.nowcodercommunity.entity.Comment;
import com.example.nowcodercommunity.entity.DiscussPost;
import com.example.nowcodercommunity.entity.Page;
import com.example.nowcodercommunity.entity.User;
import com.example.nowcodercommunity.service.*;
import com.example.nowcodercommunity.util.CommunityUtil;
import com.example.nowcodercommunity.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping(path = "/discuss")
public class DiscussPostController {

    @Autowired
    private DiscussPostService service;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LikeService likeService;

    /**
     * 查询帖子
     * @param id
     * @param model
     * @return 目标页面
     */
//    @LoginRequire
    @RequestMapping(path = "/detail/{discusspostid}",method = RequestMethod.GET)
    public String getDiscussPost(@PathVariable(name = "discusspostid") int id, Model model,Page page){
        // 查询该帖子详细信息
        DiscussPost post = service.findDiscussPostById(id);
        if(post==null){
            throw new RuntimeException("未找到对应的帖子，请检查ID");
        }
        model.addAttribute("post",post);

        // 查询作者详细信息
        User userById = userService.findUserById(post.getUserId());
        model.addAttribute("postHost",userById);

        // 查找点赞情况
        long entityLikeCount = likeService.getEntityLikeCount(CommunityConstant.ENTITY_TYPE_POST, id);
        model.addAttribute("likeCount",entityLikeCount);

        int entityLikeStatus = (hostHolder.getUser()==null) ? 0 :
                likeService.getEntityLikeStatus(userById.getId(),CommunityConstant.ENTITY_TYPE_POST,post.getId());
        model.addAttribute("likeStatus",entityLikeStatus);

        // 分页查询评论
        page.setLimit(5);
        page.setSearchPath("discuss/detail/"+post.getId());
        page.setTotalRows(post.getCommentCount());
        // 先查找回复，然后根据回复数据再添加对应的数据，包括回复用户，回复的回复，回复的回复用户，最终返回commentVoList
        List<Comment> comments = commentService.getCommentsByEntity(CommunityConstant.ENTITY_TYPE_POST, post.getId(), page.getFrom(), page.getLimit());
//        System.out.println(comments.size());
        List<Map<String,Object>> commentVOList = new LinkedList<>();

        if(comments!=null){
            for(Comment comment:comments){

                Map<String,Object> commentVo = new HashMap<>();
                commentVo.put("comment",comment);
                commentVo.put("user",userService.findUserById(post.getUserId()));
                commentVo.put("replyCount",commentService.getCountsCommentByEntity(CommunityConstant.ENTITY_TYPE_COMMENT,comment.getId()));

                long likeCount = likeService.getEntityLikeCount(CommunityConstant.ENTITY_TYPE_COMMENT,comment.getId());
                commentVo.put("likeCount",likeCount);
                int likeStatus = (hostHolder.getUser()==null) ? 0 :
                        likeService.getEntityLikeStatus(userById.getId(),CommunityConstant.ENTITY_TYPE_COMMENT,comment.getId());
                commentVo.put("likeStatus",likeStatus);

                // 查询评论的评论，不分页，直接全部查找
                List<Comment> commentsOfComment = commentService.getCommentsByEntity(CommunityConstant.ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
                List<Map<String,Object>> replyVoList = new ArrayList<>();

                if(commentsOfComment!=null){
                    for(Comment reply:commentsOfComment){
                        Map<String,Object> replyVo = new HashMap<>();

                        replyVo.put("reply",reply);
                        replyVo.put("user",userService.findUserById(reply.getUserId()));

                        long replyLikeCount = likeService.getEntityLikeCount(CommunityConstant.ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeCount",replyLikeCount);
                        int replyLikeStatus = (hostHolder.getUser()==null) ? 0 :
                                likeService.getEntityLikeStatus(userById.getId(),CommunityConstant.ENTITY_TYPE_COMMENT,reply.getId());
                        replyVo.put("likeStatus",replyLikeStatus);

                        User target = (reply.getTargetId()==0?null:userService.findUserById(reply.getTargetId()));
                        replyVo.put("target",target);

                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replies",replyVoList);
                commentVOList.add(commentVo);
            }
        }
//        System.out.println(commentVOList);
        model.addAttribute("comments",commentVOList);
        return "/site/discuss-detail";
    }

    /**
     * 发布帖子
     * @param title
     * @param content
     * @return 目标页面
     */
    @LoginRequire
    @RequestMapping(path = "/add",method = RequestMethod.POST)
    @ResponseBody
    public String addDiscussPost(String title,String content){
        User user = hostHolder.getUser();
        if (user==null){
            return CommunityUtil.getJSONString(403,"请登录后发布！");
        }

        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(title);
        post.setContent(content);
        post.setType(0);
        post.setStatus(0);
        post.setCreateTime(new Date());
        post.setCommentCount(0);
        post.setScore(0);

        service.addDiscussPost(post);

        return CommunityUtil.getJSONString(0,"发布成功！");
    }
}
